//
//  FCSelectPinVC.m
//  FundChain
//
//  Created by 肖浩然的mac on 2018/2/14.
//  Copyright © 2018年 RUIXIN. All rights reserved.
//

#import "FCSelectPinVC.h"
#import "FCAddCoinsVC.h"
@interface FCSelectPinVC (){
    UIView     *_viewNav;
}
@property (nonatomic,strong) UILabel *titlePinLabel;
@property (nonatomic,strong) UIView *sixPointView;
@property (nonatomic,strong) NSArray *numPointArr;
@property (nonatomic,strong) NSMutableArray *PINArrM;
@property (nonatomic,strong) NSMutableArray *firstPINArrM;//第一次输入
/* 记录是否通过 */
@property (assign, nonatomic) BOOL alreadyInport;

/* bgView */
@property (strong, nonatomic) UIView *bgView;

@end

@implementation FCSelectPinVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.numPointArr = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"C",@"0",@"X"];
    [FCLocalUserHelper saveIsMainVC:@"0"];
    [self setupUI];
    [self setNav];
}
#pragma mark-设置导航栏
-(void)setNav{
    self.navigationController.navigationBarHidden = YES;
    _viewNav =[UIView new];
    [self.view addSubview:_viewNav];
    [_viewNav mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                
                make.left.right.top.mas_equalTo(self.view.safeAreaInsets);
                make.height.mas_equalTo(88);
            }else{
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(64);
                make.top.mas_equalTo(0);
            }
        }else{
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(64);
            make.top.mas_equalTo(0);
        }
        
    }];
    _viewNav.backgroundColor = [UIColor clearColor];
    
    UIButton *leftBtn = [UIButton new];
    [self.view addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15*KScreenWidthScale750);
        make.centerY.mas_equalTo(_viewNav.mas_centerY).offset(8);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [leftBtn setImage:[UIImage imageNamed:@"icon_back_black"]  forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
   
    //事件
    [leftBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
   
}
-(void)leftBtnClick{
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:NO];
}
#pragma mark-设置UI
-(void)setupUI{
    
    
    CGFloat headLabelTop;
    CGFloat headBtnTop;
    CGFloat twoBtnSep;//两个按钮之间的间距
    CGFloat lineViewTop;//第二条分割线
    if(iPhone4)
    {
        headLabelTop = 30*i5_i6H;
        headBtnTop = 30*i5_i6H;
        twoBtnSep = 25*i5_i6H;
        lineViewTop = 105*i5_i6H;
    }
    else if (iPhone5)
    {
        headLabelTop = 30*i5_i6H;
        headBtnTop = 30*i5_i6H;
        twoBtnSep = 25*i5_i6H;
        lineViewTop = 105*i5_i6H;
    }else if(iPhone6)
    {
        headLabelTop = 30;
        headBtnTop = 30;
        twoBtnSep = 25;
        lineViewTop = 105;
    }else if(iPhone6p)
    {
        headLabelTop = 30*i6p_6H;
        headBtnTop = 30*i6p_6H;
        twoBtnSep = 25*i6p_6H;
        lineViewTop = 105*i6p_6H;
    }else
    {
        headLabelTop = 30*iX_i6H;
        headBtnTop = 30*iX_i6H;
        twoBtnSep = 25*iX_i6H;
        lineViewTop = 105*iX_i6H;
    }
    CGFloat leftWidth = SCREEN_WIDTH/2-twoBtnSep*2-twoBtnSep/2-45;
    //设置PIN
    UILabel *titlePinLabel = [UILabel new];
    self.titlePinLabel = titlePinLabel;
    [self.view addSubview:titlePinLabel];
    [titlePinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                make.centerX.mas_equalTo(0);
                make.top.mas_equalTo((60+64)*KScreenHeightScale1334);
                
            }else{
                make.centerX.mas_equalTo(0);
                make.top.mas_equalTo((60+64)*KScreenHeightScale1334);
                
            }
        }else{
            make.centerX.mas_equalTo(0);
            make.top.mas_equalTo((60+64)*KScreenHeightScale1334);
            
        }
        
    }];
    titlePinLabel.text = Localized(@"选择你的Pin");
    titlePinLabel.font = Kfont(48);
    
    //六个显示出来的橙色圆圈
    self.sixPointView = [[UIView alloc] init];
    [self.view addSubview:self.sixPointView];
    
    [self.sixPointView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titlePinLabel.mas_bottom).offset(headBtnTop);
        make.left.mas_equalTo(self.view).offset(0);
        make.right.mas_equalTo(self.view).offset(0);
        make.height.mas_equalTo(15);
    }];
    
    //六个显示出来的红色圆圈
    for (NSInteger i=0; i<6; i++)
    {
        UIButton *headBtn = [[UIButton alloc] init];
        [headBtn setBackgroundImage:[UIImage imageNamed:@"grey_dash"] forState:UIControlStateNormal];
        
        //        headBtn.layer.cornerRadius = 7.5;
        //        headBtn.layer.masksToBounds = YES;
        headBtn.tag = 10+i;
        [_sixPointView addSubview:headBtn];
        
        [headBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_sixPointView.mas_top).offset(0);
            make.left.mas_equalTo(self.view).offset(leftWidth+i*15+i*twoBtnSep);
            make.width.mas_equalTo(15);
        }];
        
    }
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = RGB(26, 31, 37);
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(lineViewTop);
        make.left.mas_equalTo(self.view).offset(kSpacingDistance);
        make.right.mas_equalTo(self.view).offset(-kSpacingDistance);
        make.height.mas_equalTo(1);
    }];
    lineView.hidden = YES;
    CGFloat grayLeftOrigin;//最左边按钮起始位置
    CGFloat btnViewWidth;//按钮底部的View的宽高
    CGFloat separateWidth;//两个View之间横向的间隙
    CGFloat separateHeight;//两个View之间纵向的间隙
    CGFloat topBtnView;
    CGFloat viewBtnSep;//两个圆之间的距离
    if(iPhone4)
    {
        topBtnView = (kDistance50+25)*i5_i6H;
        grayLeftOrigin = 105/2*i5_i6W;
        separateWidth = kDistance30*i5_i6W;
        separateHeight = kDistance30*i5_i6H;
        btnViewWidth = (SCREEN_WIDTH/2-grayLeftOrigin-separateWidth)/1.5;
        viewBtnSep = kDistance5*i5_i6H;
    }
    else if (iPhone5)
    {
        topBtnView = (kDistance50+25)*i5_i6H;
        grayLeftOrigin = 105/2*i5_i6W;
        separateWidth = kDistance30*i5_i6W;
        separateHeight = kDistance30*i5_i6H;
        btnViewWidth = (SCREEN_WIDTH/2-grayLeftOrigin-separateWidth)/1.5;
        viewBtnSep = kDistance5*i5_i6H;
    }else if(iPhone6)
    {
        topBtnView = kDistance50+25;
        grayLeftOrigin = 105/2;
        separateWidth = kDistance30;
        separateHeight = kDistance30;
        btnViewWidth = (SCREEN_WIDTH/2-grayLeftOrigin-separateWidth)/1.5;
        viewBtnSep = kDistance5;
    }else if(iPhone6p)
    {
        topBtnView = (kDistance50+25)*i6p_6H;
        grayLeftOrigin = 105/2*i6p_6W;
        separateWidth = kDistance30*i6p_6W;
        separateHeight = kDistance30*i6p_6H;
        btnViewWidth = (SCREEN_WIDTH/2-grayLeftOrigin-separateWidth)/1.5;
        viewBtnSep = kDistance5*i6p_6H;
    }else
    {
        topBtnView = (kDistance50+25)*iX_i6H;
        grayLeftOrigin = 105/2*iX_i6W;
        separateWidth = kDistance30*iX_i6W;
        separateHeight = kDistance30*iX_i6H;
        btnViewWidth = (SCREEN_WIDTH/2-grayLeftOrigin-separateWidth)/1.5;
        viewBtnSep = kDistance5*iX_i6H;
    }
    
    // 下面12个按钮
    for (NSInteger i=0; i<3; i++)
    {
        for (NSInteger j=0; j<4; j++)
        {
            UIView *btnView = [[UIView alloc] init];
            btnView.backgroundColor = HEXCOLOR(0xcccccc);
            btnView.layer.cornerRadius = btnViewWidth/2;
            [self.view addSubview:btnView];
            
            [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(lineView.mas_bottom).offset(topBtnView+j*(btnViewWidth+separateHeight));
                make.left.mas_equalTo(self.view).offset(grayLeftOrigin+i*(btnViewWidth+separateWidth));
                make.height.width.mas_equalTo(btnViewWidth);
            }];
            
            UIButton *grayBtn = [[UIButton alloc] init];
            grayBtn.backgroundColor = kWhiteColor;
            grayBtn.layer.cornerRadius = (btnViewWidth-2*viewBtnSep)/2;
            [grayBtn setTitle:self.numPointArr[3*j+i] forState:UIControlStateNormal];
            grayBtn.layer.masksToBounds = YES;
            
            
            grayBtn.tag = 100+j*3+i;
            grayBtn.titleLabel.font = Kfont(22);
            if (grayBtn.tag == 109||grayBtn.tag == 111)
            {
                grayBtn.titleLabel.font = Kfont(60);
            }else
            {
                grayBtn.titleLabel.font = Kfont(60);
            }
            [grayBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [grayBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateHighlighted];
            [grayBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
            [grayBtn setTitleColor:HEXCOLOR(0x660000) forState:UIControlStateHighlighted];
            
            [grayBtn addTarget:self action:@selector(grayBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [btnView addSubview:grayBtn];
            
            [grayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(btnView.mas_top).offset(viewBtnSep);
                make.left.mas_equalTo(btnView.mas_left).offset(viewBtnSep);
                make.height.width.mas_equalTo(btnViewWidth-2*viewBtnSep);
            }];
        }
    }
    
    
}

- (void)grayBtnAction:(UIButton *)grayBtn
{
    
    if (grayBtn.tag == 109)
    {
        //CLR按钮，清除全部
        if (self.PINArrM.count>0)
        {
            [self.PINArrM removeAllObjects];
        }
        
    }else if (grayBtn.tag == 111)
    {
        //DEL按钮
        if (self.PINArrM.count>0)
        {
            [self.PINArrM removeLastObject];
        }
    }else
    {
        //数字
        NSNumber *number;
        if (grayBtn.tag==110)
        {
            //0
            number = [NSNumber numberWithInteger:0];
        }else
        {
            //1-9
            number = [NSNumber numberWithInteger:grayBtn.tag-99];
        }
        if (self.PINArrM.count>=6)
        {
            return;
        }else
        {
            [self.PINArrM addObject:number];
        }
    }
    
    //刷新上面4个橙色按钮
    [self refreshHeadBtnView:self.PINArrM.count];
    
}
//刷新上面六个橙色按钮
- (void)refreshHeadBtnView:(NSInteger)pinCount
{
    for (NSInteger i=0; i<6; i++)
    {
        UIButton *btn = [self.view viewWithTag:10+i];
        [btn setBackgroundImage:[UIImage imageNamed:@"grey_dash"] forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor clearColor];
    }
    for (NSInteger i=0; i<pinCount; i++)
    {
        UIButton *btn = [self.view viewWithTag:10+i];
        [btn setBackgroundImage:[UIImage imageNamed:@"blue_dot"] forState:UIControlStateNormal];
    }
    //必须大于或者等于6才算通过
    if (pinCount >= 6) {
        //设置一个属性记录
        if (self.alreadyInport) {
            //之前输入过
            NSString *str1 = [self.firstPINArrM componentsJoinedByString:@""];
            NSString *str2 = [self.PINArrM componentsJoinedByString:@""];
            if ([str1 isEqualToString:str2]) {
                //输入一致进行网络请求设置Pin
                [self postNetPin];
                
            }else{
                
                [self setUpSignOutNoticView];
                
            }
        }else{
            //之前没有输入过
            self.firstPINArrM = [NSMutableArray arrayWithArray:self.PINArrM];
            self.titlePinLabel.text = Localized(@"选择你的Pin");
            //清除pin码
            [self clearPinColor];
            self.sixPointView.hidden = NO;
            self.alreadyInport = YES;
        }
        
    }
    
    
    
}



#pragma mark 退出提示
- (void)setUpSignOutNoticView {
    
    //弹框
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"提示") message:Localized(@"两次输入的PIN不一致") preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:Localized(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf singOutClick];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:Localized(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:action];
    [alertController addAction:action2];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)singOutClick
{
    //两次输入的验证PIN码不一致，返回第一次输入
    self.titlePinLabel.text = Localized(@"选择你的Pin");
    //清除pin码
    [self clearPinColor];
    self.alreadyInport = false;
    
    
}
- (void)clearPinColor
{
    for (NSInteger i=0; i<6; i++)
    {
        UIButton *btn = [self.view viewWithTag:10+i];
        btn.backgroundColor = [UIColor clearColor];
        [btn setBackgroundImage:[UIImage imageNamed:@"grey_dash"] forState:UIControlStateNormal];
    }
    [self.PINArrM removeAllObjects];
}
#pragma mark-懒加载
-(NSMutableArray *)PINArrM
{
    if (!_PINArrM)
    {
        _PINArrM = [NSMutableArray array];
    }
    return _PINArrM;
}
#pragma mark-获取添加的货币种类
-(void)pushAddCoinsVC{
    
    FCAddCoinsVC *vc = [FCAddCoinsVC new];
    [self.navigationController pushViewController:vc animated:NO];
    
    
}
#pragma mark-设置Pin的请求
-(void)postNetPin{
    
    __weak __typeof(self)wself = self;
    NSString *pinCode = [self.PINArrM componentsJoinedByString:@""];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:1];
    NSString*url = [NSString stringWithFormat:@"%@",Set_pin_URL];
    NSMutableArray *arrM = [FCLocalUserHelper getTimeAndSign];
    NSString *signStr = [NSString stringWithFormat:@"%@",arrM[1]];
    NSString *timeStr = [NSString stringWithFormat:@"%@",arrM[0]];
    [dict setObject:[FCLocalUserHelper sha1:signStr] forKey:@"sign"];
    [dict setObject:timeStr forKey:@"time"];
    [dict setObject:[FCLocalUserHelper sha1:pinCode] forKey:@"PIN"];
    [dict setObject:[FCLocalUserHelper getXidStr] forKey:@"XID"];
    
    [FCSharedNetworkTool POSTWithURLString:url parameters:dict success:^(id responseObject) {
        if (responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary *dic = responseObject;
            if([dic[@"code"] integerValue] == 200){
                //保存Pin设置的状态
                FCUserModel *model = [FCLocalUserHelper getFMDBUserInfoData];
                model.pinExists = @"1";
                [FCLocalUserHelper saveFMDBUserInfoData:model];
                //添加货币
                [self pushAddCoinsVC];
                
            }else if ([dic[@"code"] integerValue] == 406){
                
                //                [wself showAlert:Localized(@"没有通过验证")];
            }else if ([dic[@"code"] integerValue] == 400){
                //                [self pushAddCoinsVC];
                //                [wself showAlert:Localized(@"设置失败")];
            }
            
        }
        
    } faile:^(NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }
        
    }];
    
}
@end

